package com.kingbar.app.chat.kingwesocket.ws;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/ws/chat", configurator = SpringConfigurator.class)
@Component
public class ChatWebSocketEndpoint {

    // 所有连接的用户映射：userAccount -> WebSocket 实例
    private static final ConcurrentHashMap<String, ChatWebSocketEndpoint> userConnections = new ConcurrentHashMap<>();

    private Session session;
    private String userAccount;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        // 获取连接参数中的 userAccount
        Map<String, String> params = getQueryParams(session);
        this.userAccount = params.get("userAccount");

        if (userAccount == null || userAccount.isEmpty()) {
            sendMessage("连接失败：缺少 userAccount 参数");
            try {
                session.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        userConnections.put(userAccount, this);
        System.out.println(userAccount + " 已连接，当前在线人数：" + userConnections.size());
        sendMessage("欢迎你，" + userAccount + "！");
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("收到 " + userAccount + " 的消息: " + message);

        // 假设消息格式是: targetUserAccount|内容
        String[] parts = message.split("\\|", 2);
        if (parts.length != 2) {
            sendMessage("消息格式错误，应为：目标用户|消息内容");
            return;
        }

        String targetUser = parts[0];
        String content = parts[1];

        ChatWebSocketEndpoint targetConnection = userConnections.get(targetUser);
        if (targetConnection != null) {
            targetConnection.sendMessage("来自 " + userAccount + " 的私信：" + content);
        } else {
            sendMessage("用户 " + targetUser + " 不在线。");
        }
    }

    @OnClose
    public void onClose() {
        if (userAccount != null) {
            userConnections.remove(userAccount);
            System.out.println(userAccount + " 连接关闭，当前在线人数：" + userConnections.size());
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.err.println("用户 " + userAccount + " 的连接发生错误：" + error.getMessage());
    }

    private void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Map<String, String> getQueryParams(Session session) {
        Map<String, String> params = new ConcurrentHashMap<>();
        session.getRequestParameterMap().forEach((k, v) -> {
            if (!v.isEmpty()) {
                params.put(k, v.get(0));
            }
        });
        return params;
    }
}